<template>
  <div>
    <div class="author-wrap aic flex">
      <div class="author-label">作者:</div>
      <div class="author-value">
        <el-input v-model="author" placeholder="请输入作者"></el-input>
      </div>
    </div>
    <div class="title-wrap aic flex">
      <div class="title-label">标题:</div>
      <div class="title-value">
        <el-input v-model="title" placeholder="请输入标题"></el-input>
      </div>
    </div>
    <div class="subTitle-wrap aic flex">
      <div class="subTitle-label">副标题:</div>
      <div class="subTitle-value">
        <el-input v-model="subTitle" placeholder="请输入副标题"></el-input>
      </div>
    </div>
    <div class="keyWord-wrap aic flex">
      <div class="keyWord-label">关键词:</div>
      <div class="keyWord-value">
        <el-input v-model="keyWord" placeholder="请输入关键词"></el-input>
      </div>
    </div>
    <div class="desc-wrap aic flex">
      <div class="desc-label">描述:</div>
      <div class="desc-value">
        <el-input
          v-model="desc"
          type="textarea"
          placeholder="请输入描述"
        ></el-input>
      </div>
    </div>
    <div class="editor-box">
      <!-- 自定义上传图片 -->
      <el-upload
        class="avatar-uploader"
        :action="serverUrl"
        name="img"
        :show-file-list="false"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :before-upload="beforeUpload"
      >
      </el-upload>
      <section class="container">
        <div
          class="quill-editor"
          :content="content"
          v-quill:myQuillEditor="editorOption"
          :style="cusStyle"
          :width="toolBarwidth"
          @change="handleEditorChange"
          ref="myQuillEditor"
        ></div>
      </section>
    </div>
    <button @click="addMsg">保存</button>
  </div>
</template>

<script>
import { addMsgApi } from '@/plugins/api'
export default {
  props: {
    // 配置项
    options: {
      type: Object,
      default() {
        return {}
      },
    },
    // 自定义样式
    cusStyle: {
      type: String,
      default: '',
    },
    // 宽度
    toolBarwidth: {
      type: String,
      default: '100%',
    },
    maxLength: {
      type: Number,
      default: 100,
    },
  },
  data() {
    // 初始化编辑器功能
    const toolbarOptions = [
      ['bold', 'italic', 'underline', 'strike'], //加粗，斜体，下划线，删除线
      ['blockquote', 'code-block'], //引用，代码块
      [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
      [{ list: 'ordered' }, { list: 'bullet' }], //列表
      [{ script: 'sub' }, { script: 'super' }], // 上下标
      [{ indent: '-1' }, { indent: '+1' }], // 缩进
      [{ direction: 'rtl' }], // 文本方向
      [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
      [{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题
      [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
      [{ font: [] }], //字体
      [{ align: [] }], //对齐方式
      ['link', 'image', 'video'],
      ['clean'], //清除字体样式
    ]
    return {
      // 内容
      content: '',
      author: '',
      title: '',
      subTitle: '',
      keyWord: '',
      desc: '',
      // serverUrl: env[process.env.MODE].BASE_URL, // 这里写你要上传的图片服务器地址
      serverUrl: '#', // 这里写你要上传的图片服务器地址
      editorOption: {
        /* quill options */
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              // 重写上传图片的方法
              image: function (value) {
                if (value) {
                  // 打开图片上传的方法
                  document.querySelector('.avatar-uploader input').click()
                } else {
                  this.quill.format('image', false)
                }
              },
            },
          },
        },
      },
    }
  },
  mounted() {
    // let quillEditor = document.querySelectorAll('.ql-container')
    // let newArr = Array.from(quillEditor)
    // if (newArr.length < 3) return
    // newArr.forEach(item => {
    //   item.appendChild(this.createSpan())
    // })

    this.$nextTick(() => {
      let quill = document.querySelectorAll('.ql-toolbar')
      Array.from(quill).forEach((item) => {
        item.style.width = this.toolBarwidth
      })
    })
  },
  methods: {
    // 创建span
    createSpan() {
      let spana = document.createElement('span')
      spana.className = 'suffix-counter'
      let ema = document.createElement('em')
      ema.innerHTML = `${this.textLength}`
      let txt = document.createTextNode(`/${this.maxLength}`)
      spana.appendChild(ema)
      spana.appendChild(txt)
      return spana
    },
    handleEditorChange(e) {
      // 赋值到data中
      this.content = e.html
    },
    // 调用保存
    async addMsg() {
      let params = {
        content: this.content,
        author: this.author,
        title: this.title,
        subTitle: this.subTitle,
        keyWord: this.keyWord,
        desc: this.desc,
      }
      let res = await addMsgApi(params)
      console.log(res)
    },
    // 富文本图片上传前
    beforeUpload() {
      // 显示loading动画
      this.quillUpdateImg = true
    },

    // 注意:这里的做法是没有上传图片的接口,所以做法是需要获取本地路径
    uploadSuccess(res, file) {
      // 这里是获取本地路径
      let URL = window.URL || window.webkitURL
      let path = URL.createObjectURL(file.raw)
      // 因为下面的insertEmbed方法不接收'blob:',所以要先去掉'blob:'
      path = path.replace('blob:', '')
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.__quill
      let editor = document.getElementsByClassName('ql-editor')[0]
      // 如果上传成功
      // 获取光标所在位置
      let length = quill.getSelection().index
      // 插入图片  path为本地获取的图片地址
      quill.insertEmbed(length, 'image', path)
      // 先去掉blob:
      editor.innerHTML = editor.innerHTML.replaceAll(/blob:/g, '')
      console.log(editor.innerHTML)
      // 再加上blob:
      editor.innerHTML = editor.innerHTML.replaceAll(
        /img src="/g,
        'img src="blob:'
      )
      // 调整光标到最后(好像没有什么用)
      quill.setSelection(length + 2)
      // loading动画消失
      this.quillUpdateImg = false
    },

    // 富文本图片上传失败
    uploadError() {
      // loading动画消失
      this.quillUpdateImg = false
      this.$message.error('图片插入失败')
    },
  },
}
</script>

 
<style lang="less" scoped>
.editor-box {
  /deep/ .ql-toolbar.ql-snow {
    // width: 500px;
  }
  /deep/ .ql-editor {
    min-height: 90px;
  }
  /deep/ .ql-editor ol,
  .ql-editor ul {
    padding-left: 0;
  }
}
// .ql-toolbar.ql-snow {
//   width: 500px;
// }
// .ql-editor ol, .ql-editor ul {
//   padding-left: 0;
// }

.suffix-counter {
  position: absolute;
  right: 0;
  bottom: 0;
  padding: 0 4px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-size: 12px;
  color: grey;
}

.aic {
  align-items: center;
}
</style>
